import VueRouter from 'vue-router'
import Vue from "vue";
import Login from '@/views/login/login.vue'
import store from "../store";
import {getLoginUserInfo} from '@/api/loginApi'
import initMenu from '@/utils/menu.js'
import {Message} from "element-ui";

Vue.use(VueRouter)


// 路由
const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('@/views/home/home.vue'),
      meta: {
        title: '首页',
        type: 0
      }
    }
  ]
})



const whiteList = ['/'] // 登录白名单
// 导航前置守卫
router.beforeEach((to,from,next) => {
  if(sessionStorage.getItem('token')){
    // 判断是否跳转到外部链接
    if (to.path.includes('http')) {
      let index = to.path.indexOf('http');
      window.open(to.path.slice(index))
      return
    }

    initMenu(router,store)
    // 获取用户信息
    if(!sessionStorage.getItem('userinfo')){
      getLoginUserInfo()
    }

    if (to.path === '/'){
      next('/home')
    }else {
      next()
    }
  }else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 防止死循环
      next()
    } else {
      next(`/?redirect=${to.path}`)
      Message.info('请登录')
    }
  }
})


export default router
